package com.fjnldx.mes.service.shiftManagement;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fjnldx.mes.domain.domainReq.AddSchedulingShift;
import com.fjnldx.mes.domain.domainReq.Id;
import com.fjnldx.mes.domain.domainReq.IdList;
import com.fjnldx.mes.domain.domainReq.QuerySchedulingShift;
import com.fjnldx.mes.domain.domainRes.Result;
import com.fjnldx.mes.domain.domainRes.SchedulingShiftSystemRes;
import com.fjnldx.mes.domain.enums.GXEnum;
import com.fjnldx.mes.domain.enums.WeekEnum;
import com.fjnldx.mes.domain.pojo.SchedulingShift;
import com.fjnldx.mes.domain.pojo.SchedulingShiftSystem;
import com.fjnldx.mes.mapper.shiftManagement.SchedulingShiftMapper;
import com.fjnldx.mes.mapper.shiftManagement.SchedulingShiftSystemMapper;
import com.fjnldx.mes.utils.Common;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ShiftManageService {
    @Resource
    SchedulingShiftSystemMapper schedulingShiftSystemMapper;
    @Resource
    SchedulingShiftMapper schedulingShiftMapper;
    @Resource
    Common common;
    private final Logger logger = LoggerFactory.getLogger(ShiftManageService.class);


    public Result queryShiftSystem() {
        QueryWrapper<SchedulingShiftSystem> wrapper = new QueryWrapper<>();
        wrapper.groupBy("shiftType");
        wrapper.orderByAsc("orderId");
        List<SchedulingShiftSystem> shiftTypes = schedulingShiftSystemMapper.selectList(wrapper);

        List<SchedulingShiftSystemRes> result = new ArrayList<>();
        for (SchedulingShiftSystem s : shiftTypes) {
            String shiftType = s.getShiftType();
            SchedulingShiftSystemRes schedulingShiftSystemRes = new SchedulingShiftSystemRes();
            List<String> bcList = new ArrayList<>();

            schedulingShiftSystemRes.setId(s.getId());
            schedulingShiftSystemRes.setShiftType(shiftType);

            wrapper.clear();
            wrapper.eq("shiftType", shiftType);
            List<SchedulingShiftSystem> bcs = schedulingShiftSystemMapper.selectList(wrapper);
            for (SchedulingShiftSystem b : bcs) {
                bcList.add(b.getBc());
            }
            schedulingShiftSystemRes.setBcList(bcList);
            result.add(schedulingShiftSystemRes);
        }
        return Result.success(result);
    }

    public Result deleteShiftSystem(Id data) {
        Integer id = data.getId();
        QueryWrapper<SchedulingShiftSystem> wrapper = new QueryWrapper<>();
        SchedulingShiftSystem schedulingShiftSystem = schedulingShiftSystemMapper.selectById(id);
        wrapper.eq("shiftType", schedulingShiftSystem.getShiftType());
        schedulingShiftSystemMapper.delete(wrapper);
        return Result.success("删除成功");
    }

    public Result updateShiftSystem(SchedulingShiftSystemRes params) {
        Integer id = params.getId();
        this.deleteShiftSystem(new Id(id));
        this.addShiftSystem(params);
        return Result.success("更新成功");
    }

    public Result addShiftSystem(SchedulingShiftSystemRes params) {
        String shiftType = params.getShiftType();
        List<String> bcList = params.getBcList();

        QueryWrapper<SchedulingShiftSystem> wrap = new QueryWrapper<>();
        wrap.eq("shiftType", shiftType);
        Integer count = schedulingShiftSystemMapper.selectCount(wrap);
        if (count > 0) {
            return Result.error("已存在该班制");
        }
        QueryWrapper<SchedulingShiftSystem> wrapper = new QueryWrapper<>();
        wrapper.select("MAX(orderId) as orderId");
        SchedulingShiftSystem shiftSystem = schedulingShiftSystemMapper.selectOne(wrapper);
        Integer orderId = shiftSystem.getOrderId();
        SchedulingShiftSystem schedulingShiftSystem = new SchedulingShiftSystem();
        schedulingShiftSystem.setShiftType(shiftType);
        schedulingShiftSystem.setOrderId(orderId + 1);
        for (String b : bcList) {
            schedulingShiftSystem.setBc(b);
            schedulingShiftSystemMapper.insert(schedulingShiftSystem);
        }
        return Result.success("添加成功");
    }

    public Result deleteShift(IdList params) {
        List<Integer> idList = params.getIdList();
        QueryWrapper<SchedulingShift> shiftWrapper = new QueryWrapper<>();
        ArrayList<String> bhList = new ArrayList<>();
        for (Integer id : idList) {
            SchedulingShift schedulingShift = schedulingShiftMapper.selectById(id);
            bhList.add(schedulingShift.getBh());
        }
        shiftWrapper.in("bh", bhList);
        schedulingShiftMapper.delete(shiftWrapper);
        return Result.success("删除成功");
    }

    public Result updateShift(AddSchedulingShift params) {
        String bh = params.getBh();
        QueryWrapper<SchedulingShift> shiftWrapper = new QueryWrapper<>();
        shiftWrapper.eq("bh", bh);
        schedulingShiftMapper.delete(shiftWrapper);
        this.addShift(params, bh);
        return Result.success("更新成功");
    }

    public Result queryShiftDetail(String bh) {
        QueryWrapper<SchedulingShift> shiftWrapper = new QueryWrapper<>();
        shiftWrapper.eq("bh", bh);
        List<SchedulingShift> schedulingShifts = schedulingShiftMapper.selectList(shiftWrapper);
        return Result.success(schedulingShifts);
    }

    public Result queryShift(QuerySchedulingShift params) {
        String bh = params.getBh();
        String org = params.getOrg();
        String cj = params.getCj();
        String gongxu = params.getGongxu();
        String shiftType = params.getShiftType();
        int page = params.getPage();
        int size = params.getSize();
        Page<Map<String, Object>> iPage = new Page<>(page, size);
        QueryWrapper<SchedulingShift> shiftWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(bh)) {
            shiftWrapper.eq("bh", bh);
        }
        if (StringUtils.isNotBlank(org)) {
            shiftWrapper.eq("org", org);
        }
        if (StringUtils.isNotBlank(cj)) {
            shiftWrapper.eq("cj", cj);
        }
        if (StringUtils.isNotBlank(gongxu)) {
            shiftWrapper.eq("gongxu", gongxu);
        }
        if (StringUtils.isNotBlank(shiftType)) {
            shiftWrapper.eq("shiftType", shiftType);
        }
        shiftWrapper.select("id", "bh", "org", "cj", "gongxu", "shiftType", "bcInit", "CONCAT(DATE_FORMAT(MIN(startTime),'%Y-%m-%d'),'~',DATE_FORMAT(MAX(endTime),'%Y-%m-%d')) executionTime");
        shiftWrapper.groupBy("bh");
        Page<Map<String, Object>> schedulingShiftPage = schedulingShiftMapper.selectMapsPage(iPage, shiftWrapper);
        return Result.success(schedulingShiftPage);
    }

    public Result addShift(AddSchedulingShift params, String uuid) {
        String org = params.getOrg();
        String cj = params.getCj();
        String gongxu = params.getGongxu();
        String shiftType = params.getShiftType();
        LocalDate startTime = params.getStartTime();
        LocalDate endTime = params.getEndTime();
        String bcInit = params.getBcInit();
        if ("络筒".equals(gongxu) && !"三班制".equals(shiftType)) {
            return Result.error("络筒仅能为三班制");
        }
        if (!"络筒".equals(gongxu) && !"两班制".equals(shiftType)) {
            return Result.error("细纱+前纺仅能为两班制");
        }

        // 校验初始班次是否在该班制内
        QueryWrapper<SchedulingShiftSystem> shiftSystemWrapper = new QueryWrapper<>();
        shiftSystemWrapper.eq("shiftType", shiftType);
        List<SchedulingShiftSystem> systems = schedulingShiftSystemMapper.selectList(shiftSystemWrapper);
        List<SchedulingShiftSystem> shiftSystemsFlag = systems.stream().filter(item -> bcInit.equals(item.getBc())).collect(Collectors.toList());
        if (shiftSystemsFlag.size() == 0) {
            return Result.error("初始班次不在该班制范围内");
        }

        // 获得两个时间段中间的日期
        List<LocalDate> dateBetween = common.findLocalDateBetween(startTime, endTime);
        QueryWrapper<SchedulingShift> schedulingShiftQueryWrapper = new QueryWrapper<>();
        schedulingShiftQueryWrapper.eq("org", org);
        schedulingShiftQueryWrapper.eq("cj", cj);
        schedulingShiftQueryWrapper.eq("gongxu", gongxu);
        schedulingShiftQueryWrapper.notIn("DATE_FORMAT(startTime, '%Y-%m-%d')", dateBetween);
        Integer count = schedulingShiftMapper.selectCount(schedulingShiftQueryWrapper);
        if (count > 0) {
            return Result.error(org + "-" + cj + "-" + gongxu + "已存在该时间段的轮班安排");
        }
        SchedulingShift shift = new SchedulingShift();
        shift.setOrg(org);
        shift.setCj(cj);
        shift.setGongxu(gongxu);
        shift.setShiftType(shiftType);
        shift.setBcInit(bcInit);
        shift.setBh(uuid);
        int m = 0;
        if ("乙班".equals(bcInit)) {
            m = 1;
        }
        if ("丙班".equals(bcInit)) {
            m = 2;
        }
        // 批量插入
        List<SchedulingShift> insertShift = new ArrayList<>();
        // 前纺+细纱
        for (int i = 0; i < dateBetween.size(); i++) {
            LocalDateTime timeNode0 = common.getTimeNode(dateBetween.get(i), 0);
            LocalDateTime timeNode8 = common.getTimeNode(dateBetween.get(i), 8);
            LocalDateTime timeNode12 = common.getTimeNode(dateBetween.get(i), 12);
            LocalDateTime timeNode16 = common.getTimeNode(dateBetween.get(i), 16);
            LocalDateTime timeNode24 = common.getTimeNode(dateBetween.get(i), 24);
            if (GXEnum.Xs.getVal().equals(gongxu) || GXEnum.Cs.getVal().equals(gongxu) || GXEnum.Bt.getVal().equals(gongxu) || GXEnum.Sm.getVal().equals(gongxu) || GXEnum.Dc.getVal().equals(gongxu) || GXEnum.Zm.getVal().equals(gongxu) || GXEnum.Km.getVal().equals(gongxu)) {
                if (WeekEnum.Monday.getVal().equals(String.valueOf(dateBetween.get(i).getDayOfWeek()))) {
                    shift.setBc(m % 2 == 0 ? "甲班" : "乙班");
                    m++;
                    shift.setStartTime(timeNode0);
                    shift.setEndTime(timeNode8);
                    insertShift.add(new SchedulingShift(shift));

                    shift.setBc(m % 2 == 0 ? "甲班" : "乙班");
                    m++;
                    shift.setStartTime(timeNode8);
                    shift.setEndTime(timeNode16);
                    insertShift.add(new SchedulingShift(shift));

                    shift.setBc(m % 2 == 0 ? "甲班" : "乙班");
                    m++;
                    shift.setStartTime(timeNode16);
                    shift.setEndTime(timeNode24);
                    insertShift.add(new SchedulingShift(shift));
                } else {
                    shift.setBc(m % 2 == 0 ? "甲班" : "乙班");
                    m++;
                    shift.setStartTime(timeNode0);
                    shift.setEndTime(timeNode12);
                    insertShift.add(new SchedulingShift(shift));

                    shift.setBc(m % 2 == 0 ? "甲班" : "乙班");
                    m++;
                    shift.setStartTime(timeNode12);
                    shift.setEndTime(timeNode24);
                    insertShift.add(new SchedulingShift(shift));
                }

            } else if (GXEnum.Lt.getVal().equals(gongxu)) {
                // 周二倒班
                if (i != 0 && WeekEnum.Tuesday.getVal().equals(String.valueOf(dateBetween.get(i).getDayOfWeek()))) {
                    m = m - 2;
                }

                shift.setBc(m % 3 == 0 ? "甲班" : m % 3 == 1 ? "乙班" : "丙班");
                m++;
                shift.setStartTime(timeNode0);
                shift.setEndTime(timeNode8);
                insertShift.add(new SchedulingShift(shift));

                shift.setBc(m % 3 == 0 ? "甲班" : m % 3 == 1 ? "乙班" : "丙班");
                m++;
                shift.setStartTime(timeNode8);
                shift.setEndTime(timeNode16);
                insertShift.add(new SchedulingShift(shift));

                shift.setBc(m % 3 == 0 ? "甲班" : m % 3 == 1 ? "乙班" : "丙班");
                m++;
                shift.setStartTime(timeNode16);
                shift.setEndTime(timeNode24);
                insertShift.add(new SchedulingShift(shift));

            } else {
                return Result.error("暂无该工序");
            }
        }
        for (SchedulingShift s : insertShift) {
            System.out.println(s.toString());
        }
        schedulingShiftMapper.insertScheduleShift(insertShift);
        return Result.success("添加成功");
    }

}
